<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Requests;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Validator;
use App\Http\Controllers\Controller;
use Image;
use App\Adp;
use App\Ad;



class AdvertisementController extends Controller
{
	
	/**
	 * 设置分页大小
	 */
	public $pageSize = null;
	
	
	public function __construct()
	{
		$this->pageSize	 = CS('admin_page_size')!=''?CS('admin_page_size'):20;
	}

	
	
	/**
	 * 广告位列表
	 */
	public function adp(Request $req)
	{
		//权限验证
		if(!in_array('adp_list',session('access')))
		{
			return redirect()->action('Admin\IndexController@tips',['sec'=>'3','act'=>'fail',
				'info' => trans('admin.access_fail'),
				'url' => url('admin/info')
			]);
		}
		
		
		$title = trans('admin.adp_list');
		$data = Adp::paginate($this -> pageSize);
		return view('admin.advertisement.adp_list',['title'=>$title,
			'data' => $data,
		]);
	}
	
	
	
	/**
	 * 广告位添加
	 */
	public function adpAdd(Request $req)
	{
		//权限验证
		if(!in_array('adp_add',session('access')))
		{
			return redirect()->action('Admin\IndexController@tips',['sec'=>'3','act'=>'fail',
				'info' => trans('admin.access_fail'),
				'url' => url('admin/info')
			]);
		}
		
		if($req->isMethod('get'))
		{
			$title = trans('admin.adp_add');
			return view('admin.advertisement.adp_add',[
				'title'=>$title,
			]);
		}
		else if($req->isMethod('post'))
		{
			$input = Input::except('MAX_FILE_SIZE','_token');
			//验证字段
	        $rule = [
	            'adp_name'	=> 'required|max:80',
	            'width'		=> 'required|integer',
	            'height'	=> 'required|integer',
	            'desc'		=> 'max:200',
	        ];
			
	        $message = [
	            'adp_name.required'	=> '广告位名称是必须的',
				'adp_name.max' 		=> '广告位名称长度不能大于80',
	            'width.required'	=> '宽度是必须的',	
	            'height.required'	=> '高度是必须的',	
	            'width.integer'		=> '宽度为不大于浏览器宽度的整数',	
	            'height.integer'	=> '高度为不大于浏览器高度的整数',
	            'desc.max'			=> '描述长度不能大于200',
	        ];
			
	        $validate = Validator::make($input,$rule,$message);
	        if($validate->fails())
	        {
	            return back()-> withErrors($validate)->withInput($req->all());
	        }
		
			Adp::insert(['adp_name' => trim($req->adp_name),
				'width'		=> trim($req->width),
				'height'	=> trim($req->height),
				'desc'		=> trim($req->desc),
			]);
			
			
			return redirect()->action('Admin\IndexController@tips',['sec'=>'3','act'=>'succ',
				'info' => trans('admin.add_succ'),
				'url' => url('admin/adp')
			]);
						
			
			
		}
	}





	/**
	 * 广告位编辑
	 */
	public function adpUpdate(Request $req,$id)
	{
		//权限验证
		if(!in_array('adp_edit',session('access')))
		{
			return redirect()->action('Admin\IndexController@tips',['sec'=>'3','act'=>'fail',
				'info' => trans('admin.access_fail'),
				'url' => url('admin/info')
			]);
		}
		
		if(Adp::where('adp_id',$id)->count() < 1)
		{
			return redirect('admin/adp');
		}
		
		if($req->isMethod('get'))
		{
			$title = trans('admin.adp_update');
			$adp   = Adp::where('adp_id',$id)->first();
			return view('admin.advertisement.adp_update',[
				'title' => $title,
				'adp'   => $adp,
			]);
		}
		else if($req->isMethod('post'))
		{
			$input = Input::except('MAX_FILE_SIZE','_token');
			//验证字段
	        $rule = [
	            'adp_name'	=> 'required|max:80',
	            'width'		=> 'required|integer',
	            'height'	=> 'required|integer',
	            'desc'		=> 'max:200',
	        ];
			
	        $message = [
	            'adp_name.required'	=> '广告位名称是必须的',
				'adp_name.max' 		=> '广告位名称长度不能大于80',
	            'width.required'	=> '宽度是必须的',	
	            'height.required'	=> '高度是必须的',	
	            'width.integer'		=> '宽度为不大于浏览器宽度的整数',	
	            'height.integer'	=> '高度为不大于浏览器高度的整数',
	            'desc.max'			=> '描述长度不能大于200',
	        ];
			
	        $validate = Validator::make($input,$rule,$message);
	        if($validate->fails())
	        {
	            return back()-> withErrors($validate)->withInput($req->all());
	        }
		
			Adp::where('adp_id',$id)
			->update(['adp_name' => trim($req->adp_name),
				'width'		=> trim($req->width),
				'height'	=> trim($req->height),
				'desc'		=> trim($req->desc),
			]);
			
			
			return redirect()->action('Admin\IndexController@tips',['sec'=>'3','act'=>'succ',
				'info' => trans('admin.update_succ'),
				'url' => url('admin/adp')
			]);
						
			
			
		}
	}



	/**
	 * 删除广告位
	 */
	public function adpDel(Request $req)
	{
		//权限验证
		if(!in_array('adp_del',session('access')))
		{
			return ['error'=>1,
				'message'=>'fail',
				'content'=>'没有该操作的权限!',
			];
		}
		
		$id = isset($req->id)?intval($req->id):'0';
		if(Adp::where('adp_id',$id)->count() > 0)
		{
			if(Ad::where('adp_id',$id)->count() > 0)
			{
				return [
					'error'	 =>	1,
					'message'=>	'fail',
					'content'=>	'已有广告使用该位置，无法删除!',
				];
			}
			else
			{
				Adp::where('adp_id',$id)
					->delete();
				return [
					'error'		=>	0,
					'message'	=>	'success',
					'content'	=>	'删除成功!',
				];		
			}

		}

	}
	
	
	
	
	
	
	/**
	 * 广告位列表
	 */
	public function ad(Request $req)
	{
		//权限验证
		if(!in_array('ad_list',session('access')))
		{
			return redirect()->action('Admin\IndexController@tips',['sec'=>'3','act'=>'fail',
				'info' => trans('admin.access_fail'),
				'url' => url('admin/info')
			]);
		}
		
		$adp_id 	= isset($req->adp_id)?trim($req->adp_id):'';
		$title  	= trans('admin.ad_list');
		$where 		= [];

		if($adp_id !== '')
		{
			$where  	= array_merge($where, ['advertisements.adp_id' => $adp_id]);			
		}

		$data	= Ad::leftJoin('ad_positions','advertisements.adp_id','=','ad_positions.adp_id')
					->where($where)
					->orderBy('advertisements.ad_id','desc')
					->paginate($this -> pageSize);
		$adps	= Adp::all();
		return view('admin.advertisement.ad_list',['title'=>$title,
			'data' 		=> $data,
			'adp_id'	=> $adp_id,
			'adps'		=> $adps,
		]);
	}
	
	
	
	/**
	 * 广告添加
	 */
	public function adAdd(Request $req)
	{
		//权限验证
		if(!in_array('ad_add',session('access')))
		{
			return redirect()->action('Admin\IndexController@tips',['sec'=>'3','act'=>'fail',
				'info' => trans('admin.access_fail'),
				'url' => url('admin/info')
			]);
		}
		
		if($req->isMethod('get'))
		{
			$title = trans('admin.ad_add');
			$adps	= Adp::all();
			return view('admin.advertisement.ad_add',[
				'title'	=>$title,
				'adps'	=>$adps,
			]);
		}
		else if($req->isMethod('post'))
		{
			$input = Input::except('MAX_FILE_SIZE','_token');
			//验证字段
	        $rule = [
	            'adp_id'	=> 'required|integer',
	            'ad_name'	=> 'required|max:80',
				'url'		=> 'required',
				'img'		=> 'required|mimes:jpeg,jpg,png',
				'sort_order'=> 'integer',
				'is_show'	=> 'in:0,1',
				'start_time'=> 'required',
				'end_time'	=> 'required',
	            'linkman'	=>	'max:20',
	            'phone'	=>	'max:20',
	        ];
			
	        $message = [
	            'adp_id.required'	=> '请选择广告位置',
				'adp_id.integer' 	=> '请选择广告位置',
	            'ad_name.required'	=> '广告名称是必须的',	
	            'ad_name.max'		=> '广告名称长度不能大于80',	
	            'url.required'		=> 'Url是必须的',	
	            'img.required'		=> '广告图片是必须的',	
	            'img.mimes'			=> '仅支持格式为jpeg,jpg,png的图片',	
	            'is_show.in'		=> '请选择是或否',
				'sort_order.integer' 	=> '排序为整数',
				'start_time.required' 	=> '请选择开始日期',
				'end_time.required' 	=> '请选择结束日期',
				'linkman.max'		=>  '联系人长度不能大于20',			
				'phone.max'		=>  '电话长度不能大于20',			
	        ];
			
	        $validate = Validator::make($input,$rule,$message);
	        if($validate->fails())
	        {
	            return back()-> withErrors($validate)->withInput($req->all());
	        }
		
			$ad_id = Ad::insertGetId(['adp_id' => trim($req->adp_id),
				'ad_name'		=> trim($req->ad_name),
				'url'			=> 'http://'.getUrl(trim($req->url)),
				'is_show'		=> trim($req->is_show),
				'sort_order'	=> trim($req->sort_order),
				'start_time'	=> strtotime(trim($req->start_time)),
				'end_time'		=> strtotime(trim($req->end_time)),
				'linkman'		=> trim($req->linkman),
				'phone'			=> trim($req->phone),
			]);
			
			$wh = Adp::where('adp_id',$req->adp_id)->first();
			
			//图片处理
			if(isset($input['img']))
			{				
				$path = 'uploads/advertisements/'.date('Y/m/d/');
				if(!is_dir($path))
				{
					mkdir($path,0777,true);
				}
				
				$img_ori	= Image::make($input['img'])->resize($wh->width,$wh->height);
		        $_oriPath  	= $path.rand(1111,9999).'_'.strRand(4).'.jpg';
				$img_ori->save($_oriPath);
				
				Ad::where('ad_id',$ad_id)
				->update(['img' => $_oriPath]);				
			}
			
			return redirect()->action('Admin\IndexController@tips',['sec'=>'3','act'=>'succ',
				'info' => trans('admin.add_succ'),
				'url' => url('admin/ad')
			]);
						
			
			
		}
	}








	/**
	 * 广告修改
	 */
	public function adUpdate(Request $req,$id)
	{
		//权限验证
		if(!in_array('ad_edit',session('access')))
		{
			return redirect()->action('Admin\IndexController@tips',['sec'=>'3','act'=>'fail',
				'info' => trans('admin.access_fail'),
				'url' => url('admin/info')
			]);
		}
		
				
		if(Ad::where('ad_id',$id)->count() < 1)
		{
			return redirect('admin/ad');
		}
		
		$ad = Ad::where('ad_id',$id)->first();
		$wh = Adp::where('adp_id',$ad->adp_id)->first();
		if($req->isMethod('get'))
		{
			$title = trans('admin.ad_update');
			$adps  = Adp::all();
			return view('admin.advertisement.ad_update',[
				'title'	=> $title,
				'adps'	=> $adps,
				'ad'	=> $ad,
				'wh'	=> $wh,
			]);
		}
		else if($req->isMethod('post'))
		{
			$input = Input::except('MAX_FILE_SIZE','_token');
			//验证字段
	        $rule = [
	            'adp_id'	=> 'required|integer',
	            'ad_name'	=> 'required|max:80',
				'url'		=> 'required',
				'img'		=> 'mimes:jpeg,jpg,png',
				'sort_order'=> 'integer',
				'is_show'	=> 'in:0,1',
				'start_time'=> 'required',
				'end_time'	=> 'required',
	            'linkman'	=>	'max:20',
	            'phone'	=>	'max:20',
	        ];
			
	        $message = [
	            'adp_id.required'	=> '请选择广告位置',
				'adp_id.integer' 	=> '请选择广告位置',
	            'ad_name.required'	=> '广告名称是必须的',	
	            'ad_name.max'		=> '广告名称长度不能大于80',	
	            'url.required'		=> 'Url是必须的',	
	            'img.mimes'			=> '仅支持格式为jpeg,jpg,png的图片',	
	            'is_show.in'		=> '请选择是或否',
				'sort_order.integer' 	=> '排序为整数',
				'start_time.required' 	=> '请选择开始日期',
				'end_time.required' 	=> '请选择结束日期',
				'linkman.max'		=>  '联系人长度不能大于20',			
				'phone.max'		=>  '电话长度不能大于20',			
	        ];
			
	        $validate = Validator::make($input,$rule,$message);
	        if($validate->fails())
	        {
	            return back()-> withErrors($validate)->withInput($req->all());
	        }
		
			Ad::where('ad_id',$id)
				->update(['adp_id' => trim($req->adp_id),
				'ad_name'		=> trim($req->ad_name),
				'url'			=> 'http://'.getUrl(trim($req->url)),
				'is_show'		=> trim($req->is_show),
				'sort_order'	=> trim($req->sort_order),
				'start_time'	=> strtotime(trim($req->start_time)),
				'end_time'		=> strtotime(trim($req->end_time)),
				'linkman'		=> trim($req->linkman),
				'phone'			=> trim($req->phone),
			]);
			

			
			//图片处理
			if(isset($input['img']))
			{
				
				if($ad -> img != '')
				{
					unlink(public_path($ad -> img));
				}
				
								
				$path = 'uploads/advertisements/'.date('Y/m/d/');
				if(!is_dir($path))
				{
					mkdir($path,0777,true);
				}
				
				$img_ori	= Image::make($input['img'])->resize($wh->width,$wh->height);
		        $_oriPath  	= $path.rand(1111,9999).'_'.strRand(4).'.jpg';
				$img_ori->save($_oriPath);
				
				Ad::where('ad_id',$id)
				->update(['img' => $_oriPath]);				
			}
			
			return redirect()->action('Admin\IndexController@tips',['sec'=>'3','act'=>'succ',
				'info' => trans('admin.update_succ'),
				'url' => url('admin/ad')
			]);
						
			
			
		}
	}
	
	
	/**
	 * 广告删除
	 */
	public function adDel($id)
	{
		//权限验证
		if(!in_array('ad_del',session('access')))
		{
			return redirect()->action('Admin\IndexController@tips',['sec'=>'3','act'=>'fail',
				'info' => trans('admin.access_fail'),
				'url' => url('admin/info')
			]);
		}
	
		if(Ad::where('ad_id',$id)->count() < 1)
		{
			return redirect('admin/ad');
		}
		
		$ad = Ad::where('ad_id',$id)->first();
		
		if($ad -> img != '')
		{
			unlink(public_path($ad -> img));
		}
		
		Ad::where('ad_id',$id)->delete();
		
		return redirect('admin/ad');
	
	}
	
	
	
	
	
	
	
	


}
